package com.nmdl.print.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.storage.StorageManager;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.webkit.MimeTypeMap;

import androidx.annotation.RequiresApi;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;

public class BlueUtils {
    public static File uriToFile(Uri uri, Context context) {
        String path = null;
        if ("content".equals(uri.getScheme())) {
            // 4.2.2以后
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
            if (cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                path = cursor.getString(columnIndex);
            }
            cursor.close();
            return new File(path);
        }
        return null;
    }


    public static File uriToFileApiQ(Uri uri, Context context) {
        Log.e("uriToFileApiQ", "哦==" + uri);
        File file = null;
        if (uri == null) return null;
        //android10以上转换
        if (uri.getScheme().equals(ContentResolver.SCHEME_FILE)) {
            file = new File(uri.getPath());
        } else if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
            //把文件复制到沙盒目录
            ContentResolver contentResolver = context.getContentResolver();
            String displayName = System.currentTimeMillis() + Math.round((Math.random() + 1) * 1000)
                    + "." + MimeTypeMap.getSingleton().getExtensionFromMimeType(contentResolver.getType(uri));
            Log.e("兼容", "兼容==" + displayName);
            try {
                InputStream is = contentResolver.openInputStream(uri);
                File cache = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath(), displayName);
                FileOutputStream fos = new FileOutputStream(cache);
                Log.e("uriToFileApiQ", "进入=");
//                FileUtils.copy(is, fos);//有的手机会崩溃
                FileUtils.copyInputStreamToFile(is, cache);
                Log.e("uriToFileApiQ", "来了=");
                file = cache;
                fos.close();
                is.close();
            } catch (IOException e) {
                Log.e("uriToFileApiQ", "报错=" + e.getMessage());
                e.printStackTrace();
            }
        }
        return file;
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    public static File uriToFileQ(Uri uri, Context context) {
        try {
            String docId = null;
            try {
                docId = DocumentsContract.getDocumentId(uri);
            } catch (Exception e) {
                try {
                    docId = DocumentsContract.getTreeDocumentId(uri);
                } catch (Exception ee) {
                    docId = "";
                }
            }
            String[] split = docId.split(":");
            String type = split[0];
            if (type.equals("primary")) {
                return new File(Environment.getExternalStorageDirectory() + "/" + split[1]);
            } else {
                StorageManager manager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
                Class storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
                Method getVolumeList = manager.getClass().getMethod("getVolumeList");
                Method getUuid = storageVolumeClazz.getMethod("getUuid");
                Method getState = storageVolumeClazz.getMethod("getState");
                Method getPath = storageVolumeClazz.getMethod("getPath");
                Object result = getVolumeList.invoke(manager);
                int length = java.lang.reflect.Array.getLength(result);
                for (int i = 0; i < length; i++) {
                    Object ele = java.lang.reflect.Array.get(result, i);
                    if (Environment.MEDIA_MOUNTED == getState.invoke(ele) || Environment.MEDIA_MOUNTED_READ_ONLY == getState.invoke(ele)) {
                        String uuid = (String) getUuid.invoke(ele);
                        if (uuid == type) {
                            return new File(getPath.invoke(ele) + "/" + split[1]);
                        }
                    }
                }
            }
        } catch (Exception e) {

        }
        return null;
    }
}
